window.onload=function (){
	
	
	    
	
	var min = {

		statusCode:['未开始','进行中','调度中','手动暂停','自动暂停','已终止','已完成','线路欠费','无可用坐席'],

		renwulistData:'',
		yixianglistData:'',

		renwulist:function(){ //任务列表获取

			var self = this

			this.ajaxJsonp({type:14},function(data){

				var data = data.data

				self.renwulistData = data

				$('#renList-data').html('');

				for(var i = 0 ; i < data.length ; i++){

					console.log(data[i])



					$li=`<div class="renList-data-item" >
						<div class="jobName" data-calledCount="${data[i].calledCount}" data-csJobId="${data[i].csJobId}" data-doneCount="${data[i].doneCount}" data-jobName="${data[i].jobName}" data-lostCount="${data[i].lostCount}" data-totalCount="${data[i].totalCount}" data-totalTime="${data[i].totalTime}" data-validCalledCount="${data[i].validCalledCount}" data-validTotalTime="${data[i].validTotalTime}" data-userhangupcount="${data[i].userHangUpCount}">${data[i].jobName}</div>
						<div class="status">${self.statusCode[data[i].status]}</div>
						<div><input type="text" name="" class="isUpInput" value="${data[i].isUp}"></div>
					</div>`

					$('#renList-data').append($li)

				}

				$('.jobName').click(function(){

						self.showBox();

						var jobName = $(this).text()

						self.yixiangList(jobName)

						var data = $(this).data()

						self.Echarts('#jinDu-chart'
							,[{value:data['totalcount'] - data['donecount'],name:'未完成',itemStyle:{color:'rgb(213,217,210)'},label:{position:'outside',color:'rgb(0,0,0)'}}
							,{value:data['donecount'],name:'已完成',itemStyle:{color:'rgb(172,170,252)'}}]
							,['外呼进度','总通话时长']
							,[Math.round(data['donecount']/data['totalcount']*1000) /10 + '%', parseInt(data['totaltime'] / 60) + '分' +  data['totaltime'] % 60 + '秒' ])

						self.Echarts('#jieTong-chart'
							,[{value:data['calledcount'],name:'接通个数',itemStyle:{color:'rgb(213,217,210)'},label:{position:'center',color:'rgb(0,0,0)'}}
							,{value:data['donecount'] - data['calledcount'],name:'未接通个数',itemStyle:{color:'rgb(157,226,196)'}}]
							,['电话接通率','有效通话总时长']
							,[Math.round(data['calledcount'] / data['donecount']*1000) /10 + '%',parseInt(data['validtotaltime'] / 60) + '分' +  data['validtotaltime'] % 60 + '秒'])

						self.Echarts('#youXiaoJieTong-chart'
							,[{value:data['validcalledcount'],name:'接通有效电话通数',itemStyle:{color:'rgb(213,217,210)'},label:{position:'center',color:'rgb(0,0,0)'}}
							,{value:data['calledcount'],name:'已经外呼电话通数',itemStyle:{color:'rgb(152,189,225)'}}]
							,['有效电话接通率','有效通话平均时长']
							,[Math.round(data['validcalledcount'] / data['calledcount']*1000) /10 + '%',parseInt(data['validtotaltime'] / data['validcalledcount'])])

						// console.log(data)

						self.Echarts('#guaJiLv-chart'
							,[{value:data['userhangupcount'],name:'客户挂机数',itemStyle:{color:'rgb(102,199,225)'},label:{position:'center',color:'rgb(0,0,0)'}}
							,{value:data['calledcount'],name:'接通个数',itemStyle:{color:'rgb(213,217,210)'}}]
							,['客户挂机率','']
							,[Math.round(data['userhangupcount'] / data['totalcount'] * 1000) /10 + '%',''])


						self.Echarts('#huSunLv-chart'
							,[{value:data['lostcount'],name:'呼损数',itemStyle:{color:'rgb(102,199,225)'},label:{position:'center',color:'rgb(0,0,0)'}}
							,{value:data['calledcount'],name:'接通个数',itemStyle:{color:'rgb(213,217,210)'}}]
							,['呼损率','']
							,[Math.round(data['lostcount'] / data['calledcount']*1000) /10 + '%',''])
						
						var kys = {

			                	'csjobid':'任务ID',
								'jobname':'任务名称',
								'donecount':'完成个数',
								'totalcount':'全部个数',
								'calledcount':'接通个数',
								'validcalledcount':'有效接通个数',
								'totaltime':'通话时长',
								'validtotaltime':'有效通话时长',
								'startdate':'开始时间',
								'status':'当前状态',
								'lostcount':'呼损数',
								'userhangupcount':'客户挂机数'
								}

				})

				$('.tip').click(function(){

					self.closeBox()

					var audioN = document.getElementById('audioP')

					audioN.pause()

					$('.audio').hide()

					$('#audio_i')[0].className = 'audio_i_play'


				})

				$('.tip-box').click(function(e){

					e.stopPropagation()
				})

				$('.isUpInput').change(function(){

					var  value = $(this).val()

					var jobName = $($(this).parent().prevUntil()[1]).text()

					self.isUp(value,jobName)

				})


				if(api){

					//api对象不为null关闭下拉刷新
					api.refreshHeaderLoadDone()
				}

				


			})

			this.playEnd()

		},

		showBox:function(){ //打开子菜单

			$('.tip').animate({top:0},500)
		},
		closeBox:function(){  //关闭子菜单

			$('.tip').animate({top:'100%'},500)
		},
		isUp:function(value,jobName){ //设置要抓取的任务


			this.ajaxJsonp({type:15,isUp:value,jobName:jobName},function(data){

				alert(data.msg)


			})
		},
		ajaxJsonp:function(obj,call){

   			$.ajax({

 				type:'get',
			  	url:'http://od.qumei.com:5000/appApi.php',
			  	data:obj,
			  	dataType:'jsonp',
			  	jsonp: 'fun',
			  	jsonCallback:'fun',
			  	success:function(json){

			  		call(json)

			  	},
			  	erro:function(err){
			  		call(err)

			  	} 	  	 				
   			})
   		},
   		
   		Echarts:(node,series_dataArr,titles,values)=>{

   			var node_parent = $(node).parent();

   			console.log(node_parent)


   			$li=`<div class="title">外呼进度</div>
				<div id="jinDu-chart" class="echa">
				</div>
				<div class="title-pre">8.72%</div>
				<div class="title">通话总时长</div>
				<div class="title-pre">100分47秒</div>`

			$(node_parent.find('.title')[0]).text(titles[0]?titles[0]:'')  //第一个外呼名称

			$(node_parent.find('.title')[1]).text(titles[1]?titles[1]:'') //第二个外呼名称

			$(node_parent.find('.title-pre')[0]).text(values[0]?values[0]:'') //第一个值

			$(node_parent.find('.title-pre')[1]).text(values[1]?values[1]:'') //第二个值

			//创建一个图表实例
	    	var qushiEcharts = echarts.init($(node)[0])
	    	// 指定图表的配置项和数据
	    	var option = {

			    tooltip: {
			        trigger: 'item',
			        formatter: '{a} <br/>{b}: {c} ({d}%)'
			    },
			    legend:{
			    	show:false,
			    },
			    title:{
			    	show:false,
			    	text:'',
			    	left:'center',
			    	bottom:'0.5%',
			    	textStyle:{
			    		fontWeight:'normal',
			    		fontSize:'10',
			    	},
			    },
			   
			    series: [
			        	{
			            name: '',
			            type: 'pie',
			            radius: ['50%', '70%'],
			            avoidLabelOverlap: false,
			            hoverAnimation:false,
			            hoverOffset:5,
		             	startAngle:90,
		             	clockwise:false,
			            label: {
			                show: true,
			                position: 'inside',
			                color:'break',
			                fontStyle:'normal',
			                fontSize:8,
			                margin:'10%',
			                formatter:(obj)=>{

			                	return obj.data.name +':' + obj.data.value
			                }
			            },

			            labelLine:{

			            	show:false,
			            	lenght:0,
			            	lenght2:0,
			            }
			            ,
			            emphasis: {
			                 selectorLabel: {
			                    show: false,
			                    fontSize: '5',
			                    fontWeight: 'bold'
			                }
			            }
			            ,
			            data: [
			                {value: 335, name: '直接访问'},
			                {value: 310, name: '邮件营销'},
			                {value: 234, name: '联盟广告'},
			                {value: 135, name: '视频广告'},
			                {value: 1548, name: '搜索引擎'}
			            ]
			        }
			    ]
			}

			option.series[0].data = series_dataArr

			var h = $(node).height()

			var w = $(node).width() 

			qushiEcharts.resize(

				{
					width: w,
					height: h

				}
			)

			qushiEcharts.setOption(option);





		},

    	yixiangList:function(jobName){  //获取意向客户列表及事件设置 

			var self = this

			this.ajaxJsonp({type:17,jobName:jobName},function(data){

				console.log(data)

				if(data.msg == 0){

					$('#yixiang-filed').html('');
					$('#yixiang-data-box').html('');

				}

				if(data.msg > 0){

					$('#yixiang-filed').html('');
					$('#yixiang-data-box').html('');
					$('#yixiang-filed').append(`<div>客户信息</div>
							<div>电话</div>`);

				}


				var data = data.data

				self.yixianglistData = data

				console.log(data)

				for(var i = 0 ; i < data.length ; i++){

					if(data[i].isRead == null){

						$li=`<div class="yixiang-data" data-url="${data[i].luYinUrl}" data-ConsultantName="${data[i].ConsultantName}" data-CusAddress="${data[i].CusAddress}" data-CustomerPhone="${data[i].CustomerPhone}"  data-Remark="${data[i].Remark}" data-Remark="${data[i].Remark}" data-ChannelID="${data[i].ChannelID}"  >
							<div>${data[i].Remark}</div>
							<div>${data[i].CustomerPhone}</div>
						</div>`

					}else{

						$li=`<div class="yixiang-data isRead" data-url="${data[i].luYinUrl}" data-ConsultantName="${data[i].ConsultantName}" data-CusAddress="${data[i].CusAddress}" data-CustomerPhone="${data[i].CustomerPhone}"  data-Remark="${data[i].Remark}" data-Remark="${data[i].Remark}" data-ChannelID="${data[i].ChannelID}">
							<div>${data[i].Remark}</div>
							<div>${data[i].CustomerPhone}</div>
						</div>`

					}

					

					$('#yixiang-data-box').append($li)

				}


				$('.yixiang-data').off('click')

				$('.yixiang-data').click(function(){

					var CustomerPhone = $(this).children()[1].innerHTML

					self.isReadChange(CustomerPhone,$(this))

					var url = $(this).data().url

					self.tiJsaoSCRM($(this).data())

					self.isPlayIcon(url)

					$('.audio').show()

					self.activeChange($(this)[0])

					

				})

				

			})

    	},

    	isReadChange:function(CustomerPhone,ele){ //提交已读标记

			var self = this

			this.ajaxJsonp({type:18,CustomerPhone:CustomerPhone},function(data){

				console.log(data)

			})
			
    	},

    	isPlayIcon:function(url){  //audio对象操作播放和暂停

    		var audioN = document.getElementById('audioP')

    		$('#audio_i')[0].className = 'audio_i_play'

    		audioN.pause()

    		$('#audio_i').off('click')

    		$('#audio_i').click(function(){

    			if($('#audio_i')[0].className == 'audio_i_play'){

    				audioN.src=url

    				setTimeout(() => {
					    audioN.play();
					}, 10 );

    				$('#audio_i')[0].className = 'audio_i_pasue'

    			}else if($('#audio_i')[0].className == 'audio_i_pasue'){

    				audioN.pause()

    				$('#audio_i')[0].className = 'audio_i_play'
    			}

    		})



    	},

    	activeChange:function(ele){ //当前激活的意向列表样式设置

    		var len = $(ele).siblings().length

    		var parentEle = $(ele).siblings()

    		console.log(len)

    		for(var i= 0 ; i < len ; i++){

    			parentEle[i].className = parentEle[i].className.replace(' active','')
    			
    		}

    		ele.className += ' active isRead'

    	},

    	tiJsaoSCRM:function(obj){  //SCRM提交客资函数

    		var self = this

    		$('#tijiaobut').off('click')

    		$('#tijiaobut').click(function(){
    			
    			obj['type']=16
    			obj['CusXiaoQu']=''
    			obj['CustomerName']=''
				obj['ConsultantName'] = obj.consultantname
				obj['CustomerPhone'] = obj.customerphone
				obj['ChannelID'] = obj.channelid
				obj['CusAddress'] = obj.cusaddress
				obj['CusXiaoQu'] = obj.cusxiaoqu
				obj['Remark'] = obj.remark +' 录音链接：'+ obj.url
				obj['luYinUrl'] = obj.url


    			self.ajaxJsonp(obj,function(data){
				
					if(data.StatusCode == 200){

						var data_d = JSON.parse(data.Data) 

						if(data_d.StatusCode == 200){

							alert(data_d.Data)

							var obj_i = {type:19,CustomerPhone:obj.customerphone}

							self.ajaxJsonp(obj_i,function(json){  //更改提交标记

								console.log(json)

							})

						}else if(data_d.StatusCode == 500){

							alert(data_d.ErrorMsg)

						}

					}else if(data.StatusCode == 500){

						alert('提交失败')

					}


				})



    		})


    	},
    	playEnd:()=>{  //设置audio播放结束图标更换回调

    		var audioN = document.getElementById('audioP')

    		audioN.addEventListener('ended',()=>{

    			$('#audio_i')[0].className = 'audio_i_play'

    		});


    	},
    	arrayTransp:(obj)=>{


   			var keys = Object.keys(obj[0])

   			var tra = {}

   			for(var i =0 ; i < keys.length ; i++){

   				tra[keys[i]] = []

   				for (var j =0 ; j < obj.length ; j++){

   					tra[keys[i]].push(obj[j][keys[i]])

   				}

   			}


   			return tra

   		},


	}


	min.renwulist()


	apiready = function(){
	    
	    $('#goIndex').click(function(){

	    	api.openWin({
	                     name:'首页',
	                     url:'../index.html',
	                     animation:{type:'movein',
	                                subType:'from_left'}
           })
	    })

	    api.setRefreshHeaderInfo({
		    loadingImg: 'widget://image/refresh.png',
		    bgColor: '#ccc',
		    textColor: '#fff',
		    textDown: '下拉刷新...',
		    textUp: '松开刷新...'
		}, function(ret, err) {
		    //在这里从服务器加载数据，加载完成后调用api.refreshHeaderLoadDone()方法恢复组件到默认状态
		    min.renwulist()


		});
	}



}